﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace GraphicalObjects
{
    /// <summary>Instance of a mesh.</summary>
    public class MeshInstance : GraphicalBase
    {
        public ObjectMesh m_mesh = null;
        //private Microsoft.DirectX.Direct3D.BoundingSphere m_boundingSphere;

        /// <summary>Creates anew MeshInstance</summary>
        /// <param name="mesh">Mesh to reference</param>
        public MeshInstance(ObjectMesh mesh)
        {
            m_mesh = mesh;

            //// Compute bounding sphere
            //using (Microsoft.DirectX.Direct3D.VertexBuffer buffer = m_mesh.SourceMesh.VertexBuffer)
            //{
            //    GraphicsBuffer graphicsBuffer = buffer.Lock(0, 0, Microsoft.DirectX.Direct3D.LockFlags.None);
            //    m_boundingSphere = D3D.Geometry.ComputeBoundingSphere(graphicsBuffer, m_mesh.SourceMesh.VertexCount, m_mesh.SourceMesh.VertexFormat);
            //    buffer.Unlock();
            //}
        }

        override public void ResetMesh(ref Device device)
        {
            m_mesh.LoadMesh(ref device);
        }

        override public void Draw(ref Device device)
        {
            Render(device);
        }

        /// <summary>Render the mesh.</summary>
        /// <param name="device">Direct3D device</param>
        protected void Render(Microsoft.DirectX.Direct3D.Device device)
        {
            if (device == null || m_mesh == null)
            {
                return;
            }

            device.Transform.World = Transform;
            device.VertexFormat = SourceMesh.VertexFormat;

            for (int i = 0; i < m_mesh.Materials.Length; i++)
            {
                // Set the material and texture for this subset.
                device.Material = m_mesh.Materials[i];
                device.SetTexture(0, m_mesh.Textures[i]);

                // Draw the mesh subset.
                SourceMesh.DrawSubset(i);
            }
        }

        /// <summary>Clean up resources.</summary>
        public void Dispose()
        {
            // m_mesh is disposed in CUnit.Mesh
            m_mesh = null;
        }

        /// <summary>Gets the referenced Microsoft.DirectX.Direct3D.Mesh</summary>
        public Microsoft.DirectX.Direct3D.Mesh SourceMesh
        {
            get { return m_mesh.SourceMesh; }
        }

        ///// <summary>Gets and sets the bounding radius of the mesh.</summary>
        //public float Radius
        //{
        //    get { return m_boundingSphere.Radius; }
        //    set { m_boundingSphere.Radius = Math.Abs(value); }
        //}
    }
}
